package us.codecraft.webmagic.lianjia.processor;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.lianjia.model.Area;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.List;

public class SecondHandAreaProcessor implements PageProcessor {
    private Site site = Site
            .me()
            .setDomain("sh.lianjia.com")
            .setSleepTime(3000)
            .setUserAgent(
                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");

    public void process(Page page) {
        if (page.getRequest().getUrl().equals("https://sh.lianjia.com/ershoufang/")) {
            List<String> urls = page.getHtml().xpath("/html/body/div[3]/div/div[1]/dl[2]/dd/div[1]").links().regex("(https://sh.lianjia.com/ershoufang/[a-z]+/)").all();
            if (urls.size() > 0) {
                page.addTargetRequests(urls);
            }
        } else {
            List<String> areaUrls = page.getHtml().xpath("/html/body/div[3]/div/div[1]/dl[2]/dd/div[1]/div[2]").links().regex("(https://sh.lianjia.com/ershoufang/[a-z]+/)").all();
            for (String url : areaUrls) {
                new Area()
                        .set("base_url", page.getRequest().getUrl().substring(34).replace("/",""))
                        .set("area",url.substring(34).replace("/",""))
                        .set("target_url", url)
                        .save();
            }
        }
    }

    public Site getSite() {
        return site;

    }
}
